import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONString;
import org.json.JSONStringer;

/***********************************************************************
 * Player class
 * 
 * Implements the player's ship artifact
 * 
 * Signature: public static Player create (String name, Coord position, int
 * energy); public void install (); public void destroy (); public Coord
 * position (); public String name (); public void report (String message);
 * public void changePosition (Coord target); public boolean isOrbitable ();
 * public void takeDamage (int damage); public abstract char display (); public
 * abstract String toString (); public int energy (); public void move (int dx,
 * int dy) {
 ***********************************************************************/

public class Player extends Ship implements JSONString {
  
  protected Player(String n, Coord p, int e) {
    super(n, p, e);
  }
  
  public static Player create(String n, Coord p, int e) {
    Player sh = new Player(n, p, e);
    sh.install();
    return sh;
  }
  
  public void destroy() {
    super.destroy();
    System.exit(0);
  }
  
  public char display() {
    return '>';
  }
  
  public String toString() {
    return "Player " + this.name() + " " + this.position().toString() + " @ "
        + this.energy();
  }
  
  public void report(String s) {
    System.out.println(this.name() + " reports -- " + s);
  }
  
  public static Player fromJSON(JSONObject json) {
    try {
      if(json.getString("className").equals("Player")) {
        return new Player(json.getString("name"),
                        new Coord().fromJSON(json.getJSONObject("position")),
                        json.getInt("energy"));
      } else {
        System.err.println("\"" + json.toString() + "\" does not represent a Player.");
        throw new RuntimeException("Cannot parse JSON, it is not a Player!");
      }
    } catch (JSONException e) {
      e.printStackTrace();
      throw new RuntimeException("Unrecoverable JSON error, see above stack trace");
    }
  }

  @Override
  public String toJSONString() {
    try {
      return new JSONStringer()
                        .object() 
                          .key("className")
                          .value("Player")
                          .key("name")
                          .value(this.name())
                          .key("position")
                          .value(this.position())
                          .key("energy")
                          .value(this.energy())
                        .endObject().toString();
    } catch (JSONException e) {
      e.printStackTrace();
      throw new RuntimeException("Unrecoverable JSON error, see above stack trace.");
    }
  }
}
